// Copyright (c) 2024, the WwMusic project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

package com.springfairy.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.springfairy.dao.UserMapper;
import com.springfairy.model.User;
import com.springfairy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User register(String username, String password, String email) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        if (userMapper.selectCount(wrapper) > 0) {
            throw new RuntimeException("Username already exists.");
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(password); // 密码建议加密
        user.setEmail(email);
        user.setCreatedAt(new Timestamp(System.currentTimeMillis()));
        userMapper.insert(user);
        return user;
    }

    @Override
    public User login(String username, String password,
                      HttpServletResponse response,
                      HttpSession session) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = userMapper.selectOne(wrapper);
        if (user == null || !user.getPassword().equals(password)) {
            throw new RuntimeException("Invalid username or password.");
        }

        String token = UUID.randomUUID().toString();
        Cookie tokenCookie = new Cookie("token",token);
        tokenCookie.setPath("/");
        tokenCookie.setHttpOnly(true);
        tokenCookie.setMaxAge(7 * 24 * 60 * 60 * 4); // 4周有效
        response.addCookie(tokenCookie);

        session.setAttribute("token",token);
        session.setAttribute("userId",user.getId());
        return user;
    }

}

